import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import {createReducer, on} from "@ngrx/store";
import {PostActions} from "../actions/post.actions";

export interface PostEntity {
  name: string;
  title: string;
  content: string;
}

export const entityAdapter = createEntityAdapter<PostEntity>({
  // 规范点的话，应该在post加一个id属性，否则出现重复数据，排序会出问题，添加也会不成功，这里作者懒得改了。
  // selectId: (post: PostEntity) => post.id,
});

const initialState: EntityState<PostEntity> = entityAdapter.getInitialState({
  ids: [1, 2, 3], // 设置初始的实体ID数组
  entities: {
    1: {title: 'title 1', name: "Entity 1", content: 'title 1'},
    2: {title: 'title 2', name: "Entity 2", content: 'title 2'},
    3: {title: 'title 3', name: "Entity 3", content: 'title 3'}
  }
});

// 创建reducer
export const entityPostReducer = createReducer(
  initialState,
  on(PostActions.addEntity, (state, {data}) => {
    return entityAdapter.addOne({...data}, state)
  }),
)

